package com.mingyuan.library.infra.common.utils.validate;

import com.mingyuan.library.infra.lending.patron.exception.ParameterInvalidException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;

/**
 *  验证对象属性工具类（一般针对入参DTO使用）
 * @author yangzk
 * @version 1.0.0
 * @date 2022.11.06 11:21
 */
@Component
public class ValidatorUtil {

    private static final Logger logger = LoggerFactory.getLogger(ValidatorUtil.class);

    private static Validator validator;

    /**
     * 校验对象实现，返回校验结果
     *
     * @param value 参数下逆序
     * @param groups 校验参数组
     * @date 2022.11.06 11:21
     * @return ValidationResult
     * @author yangzk
     **/
    public static ValidationResult validate(Object value, Class<?>... groups) {
        ValidationResult validationResult = new ValidationResult();
        Set<ConstraintViolation<Object>> validateSet = validator.validate(value, groups);
        if (!validateSet.isEmpty()) {
            validationResult.setHasErrors(true);
            validateSet.forEach((validation) -> {
                String errorMessage = validation.getMessage();
                String propertyName = validation.getPropertyPath().toString();
                validationResult.getErrorMessages().put(propertyName, errorMessage);
            });
        }
        return validationResult;
    }

    public static void handleValidationResult(Object value, Class<?>... groups) {
        ValidationResult result = validate(value, groups);
        if (result.isHasErrors()) {
            logger.error("请求参数校验异常：[" + result.getErrorMessage() + "]");
            throw new ParameterInvalidException(result.getErrorMessage());
        }
    }

    public static void valid(Object value, Class<?>... groups) {
        ValidationResult result = validate(value, groups);
        if (result.isHasErrors()) {
            throw new ParameterInvalidException(result.getErrorMessage());
        }
    }

    @Autowired
    public void setValidator(Validator validator) {
        ValidatorUtil.validator = validator;
    }
}
